package com.fw.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fw.util.HttpClientSendRequestUtils;

/**
 * Servlet implementation class AppServlet
 */
@WebServlet("/app")
public class AppServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AppServlet() {
	super();
	// TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	this.process(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	this.process(request, response);
    }

    private void process(HttpServletRequest request, HttpServletResponse response) {
	try {
	    String transaction_id = request.getParameter("transaction_id");
	    boolean isIdentify = this.checkConnectionMerchant("58.181.220.230", "/merchant/check", 18080, transaction_id);
	    if (isIdentify) {
		String bip = request.getParameter("bip");
		String mip = request.getParameter("mip");
		String url = request.getParameter("url");

		ConstantUtils.BIP = bip;
		ConstantUtils.MIP = mip;
		ConstantUtils.URL = url;

		request.setAttribute("bip", bip);
		request.setAttribute("mip", mip);
		request.setAttribute("url", url);

		System.out.println("================> bip : " + bip);
		System.out.println("================> mip : " + mip);
		System.out.println("================> url : " + url);

		request.getRequestDispatcher("/index.jsp").forward(request, response);
	    } else {
		response.sendRedirect("https://appserver1:8443/app/noaccess.jsp?type=merchant");
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    private boolean checkConnectionMerchant(String ipHost, String sendToPath, int port, String transaction_id) {
	Boolean success = Boolean.FALSE;
	try {
	    Map<String, String> parameters = new HashMap<String, String>();
	    parameters.put("transaction_id", transaction_id);
	    String value = HttpClientSendRequestUtils.sendRequest(HttpClientSendRequestUtils.POST_REQUEST, ipHost, sendToPath, port,
		    parameters);
	    if ("false".equals(value)) {
		return false;
	    }
	    success = Boolean.TRUE;
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return success;
    }

}
